package com.music.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.music.common.AlipayUtils;
import com.music.entity.req.CmVipReq;

import com.music.service.CmUserService;
import com.music.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping("PayController")
public class PayController {
    @Autowired
    AlipayUtils alipayUtils;
    @Autowired
    RedisUtils redisUtils;
    @Autowired
    CmUserService cmUserService;
    @RequestMapping(value = "pay", method = RequestMethod.POST)
    public void pay(HttpServletRequest req, HttpServletResponse res, @RequestBody Map map) throws AlipayApiException, IOException, ServletException {

        CmVipReq cmVipReq = new CmVipReq();
        cmVipReq.setuId((Integer)map.get("uId"));
        cmVipReq.setDesc((String)map.get("desc"));
        cmVipReq.setName((String)map.get("name"));
        cmVipReq.setTime((Integer)map.get("time"));
        cmVipReq.setMoney(Double.valueOf(map.get("money").toString()));
//        AlipayUtils alipayUtils = new AlipayUtils();
        String pay = alipayUtils.pay(req, res, cmVipReq);
        res.getWriter().write(pay);
        res.getWriter().flush();
        res.getWriter().close();
    }
    @RequestMapping("returnUrl")
    public void returnUrl(HttpServletRequest req,HttpServletResponse res) throws AlipayApiException {
        //将异步通知中收到的所有参数都存放到map中
        Map<String, String> paramsMap = convertRequestParamsToMap(req);
        //调用SDK验证签名
        System.out.println(paramsMap);
        boolean signVerified = AlipaySignature.rsaCheckV1(paramsMap, "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAs25UntqKe1VIph9GIhkUPbPF295CN1soCJptBOy3xqpWLabZdTmume0gLa6LrjjECANkpdiEwmFEOwUCgESJbp3Urh4oMNVf6h2UV0adltCgq7An9a0+GC41neglGzblvV9bmrS6jV3r/SuOuZFJMAN6lkY+9tFjzoPfdCYGgSiyrXw6hz2wOeWzgn6An82cbfqR6pHOno1APvFc6TGI0n1kck1993ZrXuDEyLdUUNE6j5tV9Pctw5xKfMlvINPoSgmZoDKFljdPfaTK2lBy+/jXsqO5qjDbKpZk/jDc03GMiBxpeeAX4L83V0W0dJbqB9odSA3xM75JaEBX0jkGeQIDAQAB", "utf-8", "RSA2");
        if(signVerified){
            // TODO 验签成功后，按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验，校验成功后在response中返回success并继续商户自身业务处理，校验失败返回failure
            System.out.println(paramsMap);
            if (paramsMap.get("trade_status").equals("TRADE_SUCCESS")){
                Cookie[] cookies = req.getCookies();
                String number=null;
                for (Cookie cook:cookies
                ) {
                    if (cook.getName().equals("token")){
                        number=cook.getValue();
                    }
                }
                redisUtils.del(number);
                //根据out_trade_no 修改 订单状态为已支付
                System.out.println(paramsMap);
                String out_trade_no = paramsMap.get("out_trade_no");
                Object o = redisUtils.get(out_trade_no);
                if (o!=null){
                    String s = JSONObject.toJSONString(o);
                    CmVipReq cmVipReq = JSON.parseObject(s, CmVipReq.class);
                    cmUserService.buyVip(cmVipReq);
                    System.out.println(cmVipReq);
                }
            }
        }else{
            // TODO 验签失败则记录异常日志，并在response中返回failure.
        }

    }
    // 将request中的参数转换成Map
    private static Map<String, String> convertRequestParamsToMap(HttpServletRequest request) {
        Map<String, String> retMap = new HashMap<String, String>();

        Set<Map.Entry<String, String[]>> entrySet = request.getParameterMap().entrySet();

        for (Map.Entry<String, String[]> entry : entrySet) {
            String name = entry.getKey();
            String[] values = entry.getValue();
            int valLen = values.length;

            if (valLen == 1) {
                retMap.put(name, values[0]);
            } else if (valLen > 1) {
                StringBuilder sb = new StringBuilder();
                for (String val : values) {
                    sb.append(",").append(val);
                }
                retMap.put(name, sb.toString().substring(1));
            } else {
                retMap.put(name, "");
            }
        }

        return retMap;
    }

    public String getToken(HttpServletRequest request) {
        //1.从cookie中获取token
        String token = "";
        Cookie[] cookies = request.getCookies();
        for (Cookie co : cookies) {
            if (co.getName().equals("token")) {
                token = co.getValue();
            }
        }
        return token;
    }

}
